//
//  MusicController.m
//  SleepingElf
//
//  Created by karong on 2023/10/16.
//

#import "MusicController.h"
#import "UIButton+ImageAlign.h"
#import <Lottie.h>
#import "UIImage+GIF.h"
#import "SleepRequest.h"
#import "SleepModel.h"
#import "HomeMoreController.h"

@interface MusicController ()
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *subTitleLabel;
@property (weak, nonatomic) IBOutlet UIView *musicView;
@property (weak, nonatomic) IBOutlet UIView *lottieView;
@property (weak, nonatomic) IBOutlet UIImageView *musicBGImageView;
@property (weak, nonatomic) IBOutlet UIImageView *musicDefaultImageView;

@property (weak, nonatomic) IBOutlet UIButton *playBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleLabelTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *musicViewTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *musicViewBottom;
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;
@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *imageArray;
@property (weak, nonatomic) IBOutlet UILabel *musicsNameLabel;

@property (nonatomic, strong) LOTAnimationView * animation;
@end

@implementation MusicController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    [self layoutMusicsName];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutDevice];
    [self layoutAnimation];
    [self addObserver];
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshMusicInfo) name:SERefreshMusicNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshMusicInfo) name:SESleepSettingNotification object:nil];
}

- (void)refreshMusicInfo {
    [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    [self layoutMusicsName];
}


- (void)layoutPlayStatus:(BOOL)play {
    self.playBtn.selected = play;
    play?[self.animation play]:[self.animation pause];
    play?[[PlayerManager shared]resume]:[[PlayerManager shared]pause];
    self.musicDefaultImageView.hidden = play;
    self.animation.hidden = !play;
    self.titleLabel.text = [[PlayerManager shared] currentPlayingMusic].title;
    self.collectBtn.selected = appUserCenter.isLogin?[[PlayerManager shared] currentPlayingMusic].is_collect:NO;
}

- (void)layoutMusicsName {
    NSMutableAttributedString * musicsName = [NSMutableAttributedString new];
    for (int i = 0; i < 3; i++) {
        UIImageView * img = self.imageArray[i];
        if (appConfig.lastMusicArray.count > 1 && i < appConfig.lastMusicArray.count) {
            MusicModel * music = appConfig.lastMusicArray[i];
            [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:music.cover] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                if (image) {
                    image = [image imageWithRenderingMode:(UIImageRenderingModeAlwaysTemplate)];
                    img.image = image;
                    img.tintColor = [UIColor colorFromHexRGB:@"ffffff"];
                }
            }];
            NSString *text = music.title;
            UIColor * color = [UIColor colorFromHexRGB:@"F2F4FC"];
            if ([[PlayerManager shared]playerVolumeWithMusic:music] == 0) {
                color = [UIColor colorFromHexRGB:@"ffffff" alpha:0.6];
            }
            NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:text
                                                                                         attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14], NSForegroundColorAttributeName: color}];
            
            if (i > 0) {
                [musicsName appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@" | "
                                                                                          attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14], NSForegroundColorAttributeName: [UIColor colorFromHexRGB:@"F2F4FC"]}]];
            }
            [musicsName appendAttributedString:attrText];
            
            
        }
        else {
            img.image = nil;
        }
    }
    self.musicsNameLabel.attributedText = musicsName;
}

-  (void)layoutDevice {
    self.titleLabelTop.constant = SEIsiPhoneX?100:52;
    self.musicViewTop.constant = SEIsiPhoneX?60:60;
    self.musicViewBottom.constant = SEIsiPhoneX?52:52;
}

- (void)layoutAnimation {
    UIImage * img = SEIMG(@"bg_wave");
    CGSize size = img.size;
    size.width += SEIsiPhoneX?80:40;
    size.height += SEIsiPhoneX?80:40;
    NSString * path = [[NSBundle mainBundle] pathForResource:@"musicWavePng" ofType:@"png"];
    NSData * gifData = [NSData dataWithContentsOfFile:path];
    UIImage * gifImage = [UIImage sd_imageWithGIFData:gifData];
    UIImageView * gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
    gifImageView.image = gifImage;
    [self.view insertSubview:gifImageView belowSubview:self.musicView];
    [gifImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.musicView).offset(2);
        make.centerY.mas_equalTo(self.musicView);
        make.size.mas_offset(size);
    }];
    self.animation = [LOTAnimationView animationNamed:@"musicWave_lottie"];
    self.animation.frame = CGRectMake(0, 0, self.lottieView.size.width, self.lottieView.size.height);
    self.animation.loopAnimation = YES;
    [self.lottieView addSubview:self.animation];
    [self.animation play];
}

- (void)loadTipAndListen {
    [SleepRequest loadTipAndListenListWithSuccess:^(id obj) {
        SleepModel * sleepModel = obj;
        self.subTitleLabel.text = SEEmptyStr(sleepModel.tip);
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)collectRequest:(MusicModel *)music {
    [SleepRequest collectMusicWithMusic_id:music.id success:^{
        music.is_collect = YES;
        [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)deleteCollectRequest:(MusicModel *)music {
    [SleepRequest deleteCollectMusicWithMusic_id:music.id success:^{
        music.is_collect = NO;
        [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)collectCustomMusicRequest:(NSString *)title {
    [SleepRequest collectCustomMusicWithMusicArray:appConfig.lastMusicArray title:title success:^{
        [[PlayerManager shared]currentPlayingMusic].is_collect = YES;
        [self layoutPlayStatus:[[PlayerManager shared] isPlaying]];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (IBAction)closeAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)collectAction:(UIButton *)sender {
    WeakSelf
    if (appUserCenter.isLogin) {
        if (sender.selected) {
            if (appConfig.lastMusicArray.count > 1) {
                ///这里没有拿不到专属白噪音的id，没办法删除
                [SEToast simple:WSLocalized(@"暂时无法删除")];
            }
            else {
                [self deleteCollectRequest:[PlayerManager shared].currentPlayingMusic];
            }
        }
        else {
            if (appConfig.lastMusicArray.count > 1) {
                UIViewController * target = [[CTMediator sharedInstance]ct_showTFAlterWithTitle:@"设置专属音频名称" content:@"" placeholderStr:WSLocalized(@"请输入音频名称") maxWordCount:15 confirm:@"" confirmHandle:^(NSString *string) {
                    [weakSelf collectCustomMusicRequest:string];
                } cancel:@""];
                target.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                target.modalPresentationStyle = UIModalPresentationCustom;
                [self presentViewController:target animated:YES completion:nil];
            }
            else {
                [self collectRequest:[PlayerManager shared].currentPlayingMusic];
            }
        }
    }
    else {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"LoginController" bundle:nil];
        UIViewController * target = [storyBoard instantiateViewControllerWithIdentifier:@"MiniLoginPop"];
        [self presentViewController:target animated:YES completion:nil];
    }
}

- (IBAction)playAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    [self layoutPlayStatus:sender.selected];
}

- (IBAction)playerSettingAction:(id)sender {
    UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"SleepController" bundle:nil];
    UIViewController * target = [storyboard instantiateViewControllerWithIdentifier:@"PlayerSettingController"];
    [self presentViewController:target animated:YES completion:nil];
}

- (IBAction)classListAction:(id)sender {
    if (appConfig.lastMusicArray.count > 1) {
        UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"HomeController" bundle:nil];
        HomeMoreController * target = [storyboard instantiateViewControllerWithIdentifier:@"HomeMoreController"];
        target.category_id = [[PlayerManager shared]currentPlayingMusic].category_id;
        [self presentViewController:target animated:YES completion:nil];
    }
    else {
        UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"SleepController" bundle:nil];
        UIViewController * target = [storyboard instantiateViewControllerWithIdentifier:@"ClassListPop"];
        [self presentViewController:target animated:YES completion:nil];
    }
}

@end
